package com.zzf.concurrent.example.design.pattern.read.writer;

import com.zzf.concurrent.example.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author GaoFeng2017
 * @date 2019/9/6 20:50
 */
@Slf4j
public class WriterWorker extends Thread {

    private ShareData shareData;
    private String nonceStr;
    private int index;

    public WriterWorker(ShareData shareData, String nonceStr) {
        this.shareData = shareData;
        this.nonceStr = nonceStr;
    }

    @Override
    public void run() {
        while (true) {
            this.write();
            TimeUtil.sleep( 100L);
        }
    }


    public void write() {
        if (index < this.nonceStr.length()) {
            char ch = this.nonceStr.charAt(index++);
            shareData.write(ch);
            log.info("writer is write, char is {}", ch);
        } else {
            index = 0;
        }
    }
}
